package com.cnstrong.webview2

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import org.json.JSONException
import org.json.JSONObject

open class CommonScanActivity : AppCompatActivity(), JsBridgeDeal {

//    protected val mMagicGestureView by lazy<MagicGestureView> {
//        findViewById(R.id.mg_gesutre)
//    }

    protected lateinit var mWebView: X5WebView

    protected val mLoadingView by lazy {
        findViewById<View>(R.id.loading_layout)
    }

    private val mImageView by lazy {
        findViewById<ImageView>(R.id.iv_loading)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_webview_scan)
        val container = findViewById<FrameLayout>(R.id.fl_webview_container)

        mWebView = provideWebViewObject(container)
        configWebView(mWebView)
        showHideLoadingView(true)
    }


    protected fun provideWebViewObject(container: FrameLayout): X5WebView {
        val webView = X5WebView(this)
        val params = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT
        )
        container.addView(webView, params)
        return webView
    }

    fun loadUrl(url: String) {
        mWebView.loadUrl(url)
    }

    private fun showHideLoadingView(show: Boolean) {
        if (show) {
            mLoadingView.visibility = View.VISIBLE
            // NOT GOOD
            Glide.with(this).asGif().load(R.drawable.load_gif).into(mImageView)
        } else {
            mLoadingView.visibility = View.GONE
        }
    }

    // 目前不存在android调用js方法的情况，暂时去除这一部分
    protected fun configWebView(webView: X5WebView) {
        val webSetting: WebSettings = webView.settings
        webSetting.allowFileAccess = true
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSetting.setSupportZoom(true)
        webSetting.builtInZoomControls = true
        webSetting.useWideViewPort = true
        webSetting.setSupportMultipleWindows(false)
        // webSetting.setLoadWithOverviewMode(true);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true)
        // webSetting.setDatabaseEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.domStorageEnabled = true
        webSetting.javaScriptEnabled = true
        webSetting.setGeolocationEnabled(true)
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE)
        webSetting.setAppCachePath(getDir("appcache", 0).path)
        webSetting.databasePath = getDir("databases", 0).path
        webSetting.setGeolocationDatabasePath(
            getDir("geolocation", 0)
                .path
        )
        webSetting.setPluginState(com.tencent.smtt.sdk.WebSettings.PluginState.ON_DEMAND)
        webSetting.userAgentString = webSetting.userAgentString + " hybrid_1.0.0 "
        mWebView.webViewClient = X5WebViewClient(mWebView, mLoadingView)
    }

    override fun getWebViewInstance(): WebView {
        return mWebView
    }

    //
    override fun registerHtmlDataHandler(name: String, handler: HtmlDataHandler) {
        mWebView.registerHtmlHandler(name, handler)
    }

    override fun unRegisterHtmlDataHandler(name: String) {
        mWebView.unRegisterHtmlHandler(name)
    }

    override fun callJs(method: String, data: String?) {
        // 还没有定义javascript:hybrid.callJs($jsonObject)
        if (TextUtils.isEmpty(method)) {
            return
        }
        val jsonObject = JSONObject()
        try {
            jsonObject.put("call", method)
            jsonObject.put("data", data)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        mWebView.loadUrl("javascript:hybrid.callJs($jsonObject)")
    }

    override fun responseJsCall(callback: String, data: String?) {
        if (TextUtils.isEmpty(callback)) {
            return
        }
        val jsonObject = JSONObject()
        try {
            jsonObject.put("callback", callback)
            jsonObject.put("data", data)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        Log.e("ResponseJsCall", jsonObject.toString())
        mWebView.loadUrl("javascript:hybrid.callback($jsonObject)")
    }


    override fun onBackPressed() {
        if (Constant.NO_NETWORK_ERROR_URL.equals(mWebView.url)) {
            super.onBackPressed()
            return
        }
        if (mWebView.canGoBack()) {
            mWebView.goBack()
            return
        }
        super.onBackPressed()

    }

    override fun onDestroy() {
        try {
            val parent = mWebView.parent
            if (parent != null) {
                (parent as ViewGroup).removeView(mWebView)
            }
            mWebView.stopLoading()
            mWebView.settings.javaScriptEnabled = false
            mWebView.removeAllViewsInLayout()
            mWebView.clearHistory()
            mWebView.removeAllViewsInLayout()
            mWebView.removeAllViews()
            mWebView.destroy()
        } catch (e: Exception) {
        } finally {
            super.onDestroy()
        }
    }
}